<template>
  <view class="product-detail-container">
    <!-- 商品图片 -->
    <view class="product-image-section">
      <image :src="productDetail.productImage" class="product-image" mode="aspectFill" />
      <view class="activity-tag">
        <text class="tag-text">{{ productDetail.activityTitle }}</text>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="product-info-section">
      <view class="product-title">{{ productDetail.productName }}</view>
      
      <!-- 价格信息 -->
      <view class="price-section">
        <view class="price-row">
          <text class="seckill-price">¥{{ productDetail.seckillPrice }}</text>
          <text class="original-price">¥{{ productDetail.originalPrice }}</text>
        </view>
        <view class="discount-info">
          <text class="discount-text">省¥{{ productDetail.discountAmount }}</text>
          <text class="discount-rate">{{ productDetail.discountRate }}%</text>
        </view>
      </view>

      <!-- 库存信息 -->
      <view class="stock-section">
        <view class="stock-info">
          <text class="stock-label">库存:</text>
          <text class="stock-value">{{ productDetail.remainingStock }}件</text>
        </view>
        <view class="sales-info">
          <text class="sales-label">已售:</text>
          <text class="sales-value">{{ productDetail.sales }}件</text>
        </view>
        <view class="limit-info">
          <text class="limit-label">限购:</text>
          <text class="limit-value">{{ productDetail.limitPerUser }}件/人</text>
        </view>
      </view>

      <!-- 活动状态 -->
      <view class="status-section">
        <view class="status-tag" :class="getStatusClass()">
          <text class="status-text">{{ getStatusText() }}</text>
        </view>
        <view v-if="productDetail.soldOut" class="sold-out-tag">
          <text class="sold-out-text">已售罄</text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <view class="detail-content">
        <view class="detail-item">
          <text class="item-label">商品ID:</text>
          <text class="item-value">{{ productDetail.productId }}</text>
        </view>
        <view class="detail-item">
          <text class="item-label">活动ID:</text>
          <text class="item-value">{{ productDetail.activityId }}</text>
        </view>
        <view class="detail-item">
          <text class="item-label">创建时间:</text>
          <text class="item-value">{{ formatTime(productDetail.createTime) }}</text>
        </view>
        <view class="detail-item">
          <text class="item-label">更新时间:</text>
          <text class="item-value">{{ formatTime(productDetail.updateTime) }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="share-btn" @click="shareProduct">分享</button>
      <button 
        v-if="!productDetail.soldOut && productDetail.remainingStock > 0"
        class="seckill-btn" 
        @click="buyNow"
      >
        立即秒杀
      </button>
      <button 
        v-else
        class="sold-out-btn" 
        disabled
      >
        已售罄
      </button>
    </view>

    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <uni-load-more status="loading" />
    </view>
  </view>
</template>

<script>
import { getSeckillProductDetail, createSeckillOrder } from '@/api/seckill'

export default {
  name: 'SeckillProductDetail',
  data() {
    return {
      productId: null,
      loading: false,
      productDetail: {}
    }
  },
  
  onLoad(options) {
    this.productId = options.id
    if (this.productId) {
      this.loadProductDetail()
    }
  },
  
  methods: {
    // 加载商品详情
    async loadProductDetail() {
      try {
        this.loading = true
        console.log('=== 加载商品详情 ===')
        console.log('商品ID:', this.productId)
        console.log('商品ID类型:', typeof this.productId)
        
        const response = await getSeckillProductDetail(this.productId)
        
        if (response.code === 200) {
          this.productDetail = response.data || {}
          console.log('商品详情:', this.productDetail)
        } else {
          throw new Error(response.msg || '获取商品详情失败')
        }
      } catch (error) {
        console.error('加载商品详情失败:', error)
        uni.showToast({
          title: '加载商品详情失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hour = date.getHours().toString().padStart(2, '0')
      const minute = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}`
    },
    
    // 获取状态样式
    getStatusClass() {
      if (this.productDetail.soldOut) {
        return 'status-sold-out'
      }
      if (this.productDetail.remainingStock <= 0) {
        return 'status-no-stock'
      }
      return 'status-available'
    },
    
    // 获取状态文本
    getStatusText() {
      if (this.productDetail.soldOut) {
        return '已售罄'
      }
      if (this.productDetail.remainingStock <= 0) {
        return '无库存'
      }
      return '可购买'
    },
    
    // 立即秒杀
    async buyNow() {
      if (this.productDetail.soldOut || this.productDetail.remainingStock <= 0) {
        uni.showToast({
          title: '商品已售罄',
          icon: 'none'
        })
        return
      }
      
      // 检查登录状态
      const userId = this.$store.state.user.id || uni.getStorageSync('userId');
      if (!userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login'
          })
        }, 1500)
        return
      }
      
      // 显示确认对话框
      uni.showModal({
        title: '确认秒杀',
        content: `确定要以 ¥${this.productDetail.seckillPrice} 的价格秒杀 ${this.productDetail.productName} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            await this.createSeckillOrder(userId)
          }
        }
      })
    },
    
    // 创建秒杀订单
    async createSeckillOrder(userId) {
      try {
        uni.showLoading({
          title: '正在创建订单...'
        })
        
        const orderData = {
          userId: userId,
          activityId: this.productDetail.activityId,
          productId: this.productDetail.id,
          productName: this.productDetail.productName,
          productImage: this.productDetail.productImage,
          seckillPrice: this.productDetail.seckillPrice,
          originalPrice: this.productDetail.originalPrice,
          unitPrice: this.productDetail.seckillPrice,
          quantity: 1,
          totalAmount: this.productDetail.seckillPrice,
          activityTitle: this.productDetail.activityTitle,
          limitPerUser: this.productDetail.limitPerUser
        }
        
        const response = await createSeckillOrder(orderData)
        
        uni.hideLoading()
        
        if (response.code === 200) {
          uni.showToast({
            title: '秒杀成功！',
            icon: 'success'
          })
          
          // 跳转到订单详情页或支付页面
          setTimeout(() => {
            uni.navigateTo({
              url: `/pages/order/detail?id=${response.data.orderId}`
            })
          }, 1500)
        } else {
          uni.showToast({
            title: response.message || '秒杀失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('创建秒杀订单失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    },
    
    // 分享商品
    shareProduct() {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.product-detail-container {
  min-height: 100vh;
  background: #f5f6f7;
  padding-bottom: 120rpx;
}

.product-image-section {
  position: relative;
  background: white;
  
  .product-image {
    width: 100%;
    height: 500rpx;
  }
  
  .activity-tag {
    position: absolute;
    top: 20rpx;
    left: 20rpx;
    background: #ff4757;
    color: white;
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
  }
}

.product-info-section {
  background: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .product-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    line-height: 1.4;
  }
  
  .price-section {
    margin-bottom: 30rpx;
    
    .price-row {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;
      
      .seckill-price {
        font-size: 48rpx;
        font-weight: bold;
        color: #ff4757;
        margin-right: 20rpx;
      }
      
      .original-price {
        font-size: 28rpx;
        color: #999;
        text-decoration: line-through;
      }
    }
    
    .discount-info {
      display: flex;
      align-items: center;
      
      .discount-text {
        font-size: 24rpx;
        color: #ff4757;
        margin-right: 12rpx;
      }
      
      .discount-rate {
        font-size: 24rpx;
        color: #ff4757;
        background: #fff0f0;
        padding: 4rpx 8rpx;
        border-radius: 4rpx;
      }
    }
  }
  
  .stock-section {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
    padding: 20rpx;
    background: #f8f9fa;
    border-radius: 12rpx;
    
    .stock-info, .sales-info, .limit-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .stock-label, .sales-label, .limit-label {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 8rpx;
      }
      
      .stock-value {
        font-size: 28rpx;
        font-weight: bold;
        color: #52c41a;
      }
      
      .sales-value {
        font-size: 28rpx;
        font-weight: bold;
        color: #ff4757;
      }
      
      .limit-value {
        font-size: 28rpx;
        font-weight: bold;
        color: #fa8c16;
      }
    }
  }
  
  .status-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .status-tag {
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
      
      &.status-available {
        background: #e8f5e8;
        color: #52c41a;
      }
      
      &.status-no-stock {
        background: #fff7e6;
        color: #fa8c16;
      }
      
      &.status-sold-out {
        background: #f5f5f5;
        color: #999;
      }
    }
    
    .sold-out-tag {
      background: #ff4757;
      color: white;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
    }
  }
}

.detail-section {
  background: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .detail-content {
    .detail-item {
      display: flex;
      justify-content: space-between;
      padding: 16rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .item-label {
        font-size: 28rpx;
        color: #666;
      }
      
      .item-value {
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  gap: 20rpx;
  
  .share-btn {
    flex: 1;
    background: #f5f5f5;
    color: #666;
    border: none;
    border-radius: 8rpx;
    padding: 20rpx 0;
    font-size: 28rpx;
  }
  
  .seckill-btn {
    flex: 2;
    background: #ff4757;
    color: white;
    border: none;
    border-radius: 8rpx;
    padding: 20rpx 0;
    font-size: 28rpx;
    font-weight: bold;
  }
  
  .sold-out-btn {
    flex: 2;
    background: #999;
    color: white;
    border: none;
    border-radius: 8rpx;
    padding: 20rpx 0;
    font-size: 28rpx;
    font-weight: bold;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}
</style> 